package com.xhwl.centiotdata.suppliersystem.zhongkong;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.common.exception.ApplicationException;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * @Author： lianghz
 * @Description：
 * @Date 2021/09/03/ 10:15
 */
@Service
public class GeneralZhongKongHandler {
    private static final Logger log = LoggerFactory.getLogger(GeneralZhongKongHandler.class);

    public JSONObject get(String path) {
        log.info("get path:{}", path);
        String result = null;
        try {
            result = HttpRequest
                    .get(path)
                    .execute()
                    .body();
        } catch (HttpException e) {
            log.error("get path:{}; request failed!", path);
            e.printStackTrace();
            throw new ApplicationException();
        }
        if (StringUtils.isEmpty(result)) {
            log.error("get path:{};result is null!", path);
            throw new BusinessException();
        }
        log.info("get path:{};result:{}", path, result);
        JSONObject resultObject = JSON.parseObject(result);
        if (resultObject == null || resultObject.getIntValue("code") != 0) {
            log.error("get path:{};message:{}", path, resultObject.getString("message"));
            throw new BusinessException("ZhongKong get failed!");
        }
        return resultObject;
    }

}
